﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using MediatorLib;
using ResourceEnumerator.Inrastructure;

namespace ResourceEnumerator.UI
{
    internal sealed class EnumeratorViewModel : NotifyPropertyChangedBase
    {
        private readonly RelayCommand _closeCommand;
        private readonly Mediator _messenger;
        private readonly IEnumerationService _enumerationService;

        private ResourceItem _selectedResource;
        private List<ResourceItem> _enumeratedResources;

        public EventHandler<ResourceSelectedEventArgs> ResourceSelected;

        internal EnumeratorViewModel(Mediator messenger, IEnumerationService enumerationService)
        {
            if (messenger == null) throw new ArgumentNullException("messenger");
            if (enumerationService == null) throw new ArgumentNullException("enumerationService");

            _messenger          = messenger;
            _enumerationService = enumerationService;
            _closeCommand       = new RelayCommand(Close);
        }

        internal async void Parse(string text)
        {
            var result = await _enumerationService.EnumerateAsync(text);
            EnumeratedResources = new List<ResourceItem>(result.OrderBy(x => x.XKey));
        }

        public ResourceItem SelectedResource
        {
            get { return _selectedResource; }
            set
            {
                if (_selectedResource == value) return;
                _selectedResource = value;
                RaisePropertyChanged(() => SelectedResource);
                RaiseResourceSelected(value.XKey);
            }
        }

        public List<ResourceItem> EnumeratedResources
        {
            get { return _enumeratedResources; }
            private set
            {
                _enumeratedResources = value;
                RaisePropertyChanged(() => EnumeratedResources);
            }
        }

        public ICommand CloseCommand => _closeCommand;

        void Close(object o)
        {
            _messenger.NotifyColleagues(Messages.RemoveAdornerContent);
        }

        void RaiseResourceSelected(string selectedResourceKey)
        {
            var temp = ResourceSelected;
            if (temp != null)
                ResourceSelected(this, new ResourceSelectedEventArgs(selectedResourceKey));
        }
    }
}
